package k8s

import (
	"github.com/google/wire"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/tools/clientcmd"
)

// Options device options of k8s
type Options struct {
	Config string `yaml:"config"`
}

// NewOptions build k8s option from viper
func NewOptions(v *viper.Viper, logger *zap.Logger) (*Options, error) {
	var err error
	o := new(Options)
	if err = v.UnmarshalKey("k8s", o); err != nil {
		return nil, errors.Wrap(err, "unmarshal k8s options error")
	}

	logger.Debug("load k8s options success", zap.Any("options", o))

	return o, err
}

// New define constructor of k8s
func New(o *Options) (dynamic.Interface, error) {
	config, err := clientcmd.BuildConfigFromFlags("", o.Config)
	if config == nil || err != nil {
		return nil, errors.Wrap(err, "build k8s config from flag error")
	}

	client, err := dynamic.NewForConfig(config)
	if err != nil {
		return nil, errors.Wrap(err, "create k8s client for config error")
	}

	return client, nil
}

// ProviderSet device provider set of k8s
var ProviderSet = wire.NewSet(NewOptions, New)
